# -*- coding: utf-8 -*-
"""
Created on Thu May 07 11:31:23 2015

@author: zhaoxp
"""

import os
import re
import smtplib
import paramiko
from string import atoi

def getconfigfilelist(dirpath):
    l=os.listdir(dirpath)
    returnlist=[]
    for i in l:
        matchObj=re.match('(TBG|LBG|EBG|MBG)_(CON|DEV|TST|PRE|QAS).properties',i)
        if(matchObj):
            returnlist.append(i)
    return returnlist

def readconfigfile(configfilepath):
    f=open(configfilepath)
    lines=f.readlines()
    f.close()
    i=0
    pmap={}
    configlist=[]
    while(i<len(lines)):
        lines[i]=lines[i].replace('\n','')
        tmp=lines[i].split('=')
        if len(tmp)>1:
            pmap[tmp[0]]=tmp[1]
        i=i+1
    if pmap.has_key('master_ip') and pmap.has_key('master_username') and pmap.has_key('master_password'):
        configlist.append(configinfo(pmap['master_ip'],pmap['master_username'],pmap['master_password'],configfilepath[len(configfilepath)-18:len(configfilepath)-11]))
    if pmap.has_key('slave1_ip') and pmap.has_key('slave1_username') and pmap.has_key('slave1_password'):
        configlist.append(configinfo(pmap['slave1_ip'],pmap['slave1_username'],pmap['slave1_password'],configfilepath[len(configfilepath)-18:len(configfilepath)-11]))
    if pmap.has_key('slave2_ip') and pmap.has_key('slave2_username') and pmap.has_key('slave2_password'):
        configlist.append(configinfo(pmap['slave2_ip'],pmap['slave2_username'],pmap['slave2_password'],configfilepath[len(configfilepath)-18:len(configfilepath)-11]))
    return configlist

def ssh_run_command(hostname,username,password,command):
    try:
        s=paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(hostname = hostname,username=username, password=password)
        stdin,stdout,stderr=s.exec_command(command,timeout=8)
        #print(type(stdout))
        #print(dir(stdout))
        relist=stdout.readlines()
        s.close()
        return relist[1:]
    except:
        print('exception druing run '+command+' on hostname = '+hostname+' username = '+username)
        return []

    

class configinfo(object):
    def __init__(self,hostname,username,password,sysid):
        self.hostname=hostname
        self.username=username
        self.password=password
        self.sysid=sysid
    def loginandcheckdisk(self,warningratio):
        #print('host ---> '+self.hostname+' start')
        diskutilist=ssh_run_command(self.hostname,self.username,self.password,'df')
        #print('host ---> '+self.hostname+'  end ')
        newlist=[]
        i=0
        relist,errorlist=[],[]
        while(i<len(diskutilist)):
            s=diskutilist[i]
            s=s.replace('\n','')
            s=re.sub('^\s*','',s)
            s=re.sub('\s*$','',s)
            #matchObj=re.match('([\w/\d]+\s+)+([0-9]{1,3})(%)\s+[\d\s%]+(/[\d\w]+)',s)
            splitnumber=len(re.split('\s*',s))
            if splitnumber==1:
                s=s+diskutilist[i+1]
                s=s.replace('\n','')
                newlist.append(s)
            elif splitnumber==6:
                newlist.append(s)
            elif splitnumber==7:
                newlist.append(s)
            elif splitnumber==5:
                pass
                #print("second half")
            else:
                print("error when processing df command result"+self.sysid+' '+self.hostname+' '+i)
            i+=1
        for i in newlist:
            #print("processing ... \n"+self.sysid+' '+self.hostname+' '+i)
            try:
                tmpgroups=re.match('([\w/\.\:\-\d]+\s+)+([0-9]{1,3})(%)\s+[\d\s%]*(/[\d\w\.\-/]*)',i)
                tmpfs=tmpgroups.group(4)
                tmpratio=tmpgroups.group(2)
                #print("processing result :")
                #print(tmpgroups.groups())
                if atoi(tmpratio) > warningratio:
                    relist.append(warninginfo(self.sysid,self.hostname,tmpfs,tmpratio+'%'))
            except:
                print("exception when processing RE "+self.sysid+' '+self.hostname+' '+i)
                errorlist.append("exception when processing RE "+self.sysid+' '+self.hostname+' '+i)
            '''
            for i in newlist:
                a=re.split('\s*',i)
                a[4]=a[4].replace('%','')
                #print(a[4])
                if len(a)!=6:
                    print("error...")
                if atoi(a[4]) > warningratio:
                    relist.append(warninginfo(self.sysid,self.hostname,a[5],a[4]+'%'))
            '''
        return [relist,errorlist]
    pass

class warninginfo(object):
    def __init__(self,sysid,hostname,fs,ratio):
        self.sysid=sysid
        self.hostname=hostname
        self.fs=fs
        self.ratio=ratio

"""
sender: sender's mail address
receivers: receivers' addresses seperated by semicolon(;)
title: mail title
message: mail content
mailServer: SMTP server
"""
def sendPlainTextMail(sender,receivers,title,message,mailServer):
    try:
        content="From: "+sender+"\n"+"To: "+receivers+"\n"+"Subject: "+title+"\n\n"+message+"\n"
        smtpObj=smtplib.SMTP(mailServer)
        #smtpObj=smtplib.SMTP()
        #smtpObj.connect(mailServer)
        #smtpObj.login("username","password")
        smtpObj.sendmail(sender,receivers,content)
        smtpObj.close()
    except SMTPException:
        print("Unable to send mail!")

if __name__=='__main__':
    print "main func ... start ..."
    
    #sendPlainTextMail('monitor@lenovo.com','zhaoxp2@lenovo.com','test title1','test mail content','smtpinternal.lenovo.com')
    #sendPlainTextMail('monitor@lenovo.com','zhaoxp2@lenovo.com','test title2','test mail content','smtpinternal.lenovo.com')

    wc_config_file_path='D:\\code\\scripts\\'
    
    filelist=getconfigfilelist(wc_config_file_path)
    #print(filelist)
    configlist=[]
    warninglist,errorlist=[],[]
    for i in filelist:
        configlist=configlist+readconfigfile(wc_config_file_path+i)
    for i in configlist:
        #print(i.sysid+' = '+i.hostname+' '+i.username+' '+i.password)
        l=i.loginandcheckdisk(90)
        warninglist=warninglist+l[0]
        errorlist=errorlist+l[1]
    
    msg=''
    for i in warninglist:
        msg=msg+i.sysid+' \t '+i.hostname+' \t '+i.fs+' \t '+i.ratio+'\n'
    msg=msg+'\n\n';
    for i in errorlist:
        msg=msg+i+'\n';
    mailtitle='Daily PLM OS disk utilization monitor result'
    #print("start to send mail "+mailtitle)
    if len(msg) > 0:
        sendPlainTextMail('disk_monitor@lenovo.com','zhaoxp2@lenovo.com;liuxt2@lenovo.com,zhangll9@lenovo.com',mailtitle,msg,'smtpinternal.lenovo.com')
    '''
    l=os.listdir(wc_config_file_path)
    for i in l:
        matchObj=re.match('(TBG|LBG|EBG|MBG)_(CON|DEV|TST|PRE|QAS).properties',i)
        if matchObj:
            print(i,"####",matchObj.group())
        print(type(matchObj))
        print(dir(matchObj))
    '''
    print "main func ...  end  ..."

